package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

func queryParams(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	name := params["name"][0]
	age := params["age"][0]
	fmt.Fprintf(w, "Parameter is %s, name=%s, age=%s \n", params, name, age)
}

func readBodyOnce(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(r.Body)
	fmt.Fprintf(w, "First time read body: %s \n", body)

	if err != nil {
		fmt.Fprintf(w, "Read body failed \n")
	}

	body, err = io.ReadAll(r.Body)
	fmt.Fprintf(w, "Second time read body: %s \n", body)

	if err != nil {
		fmt.Fprintf(w, "Read body failed \n")
	}

}

func wholeUrl(w http.ResponseWriter, r *http.Request) {
	data, _ := json.Marshal(r.URL)
	fmt.Fprintf(w, string(data))
}

func header(w http.ResponseWriter, r *http.Request) {
	myHeader := r.Header
	fmt.Fprintf(w, "eader is %s \n", myHeader)
}

func form(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Before ParseForm is %s \n", r.Form)
	err := r.ParseForm()
	if err != nil {
		fmt.Fprintf(w, "Parse form error: %s \n", r.Form)
	}
	fmt.Fprintf(w, "After ParseForm is %s \n", r.Form)
}

func main() {
	server := NewHttpServer("test-server")

	server.Route("/readBodyOnce", readBodyOnce)
	server.Route("/wholeUrl", wholeUrl)
	server.Route("/queryParams", queryParams)
	server.Route("/header", header)
	server.Route("/form", form)
	server.Start(":8080")
}
